<template>
  <div>
    <a-card
      :bordered="false"
      :style="{marginTop: '20px'}"
      title="对应绩效">
      <div class="table-operator">
        <a-row :gutter="24">
          <a-col :md="3">
            <a-button
              type="primary"
              icon="plus"
              @click="createList">关联版本</a-button>
          </a-col>
          <a-col :md="7"><span>当前版本</span>
            <a-select
              style="width: 200px;margin-left: 15px"
              v-model="versionName"
              placeholder="请选择版本"
              :disabled="hasGrant">
              <a-select-option
                v-for="i in allVersion"
                :key="i"
                :value="i">
                {{ i }}
              </a-select-option>
            </a-select>
            <div
              style="display: inline;margin-left: 10px;"
              title="刷新"
              @click="refresh">
              <a-icon
                style="cursor: pointer"
                type="undo" />
            </div>
          </a-col>
          <a-col>
            <h3>{{ hasGrant ? `已有发放记录，无法切换版本，需要切换需要到提成记录页面撤销已发放金额` : '' }}
            </h3>
          </a-col>
        </a-row>
      </div>
      <div>
        <a-spin :spinning="loading">
          <s-table
            ref="table"
            size="default"
            :rowKey="'id'"
            :columns="columns"
            :data="loadData"
            :expandedRowsChange="expandedRowsChange"
            :expand="expand"
            :customRow="tableCustomRow"
            :showPagination="false">
            <!-- <span
              slot="job2"
              slot-scope="text">
              <template>
                <span>{{ labels.find(item => item.value === text).label }}</span>
              </template>
            </span> -->
            <!-- incentiveName -->
            <!-- <span
              slot="incentiveName"
              slot-scope="text, record">
              <template>
                <div :style="{ marginLeft: record.level ? `${record.level*15}px` : '50px'}">
                  <ellipsis
                    :length="20"
                    tooltip>{{ text }}</ellipsis>
                </div>
              </template>
            </span> -->

            <span
              slot="action"
              slot-scope="text, record">
              <template>
                <!-- v-if="record.level === 1 && record.job2 !== 1 && record.job2 !== 2 && record.job2 !== 9" -->

                <a
                  v-if="record.pingding"
                  style="margin-right: 8px"
                  @click="() => { showEvaModal(record) }">考核评定</a>
                <!-- v-if="record.level === 2" -->
                <a
                  v-if="record.fenpei"
                  @click="() => { showUserModal(record) }">分配</a>
                <!-- v-if="record.level === 2" -->
                <a
                  v-if="record.delete"
                  @click="() => { deletePer(record) }">删除</a>
              </template>
            </span>
          </s-table>
        </a-spin>
      </div>
      <create-form
        ref="createModal"
        :visible="visible"
        :isEdit="isEdit"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk" />
      <user-form
        ref="userModal"
        :visible="userVisible"
        :allUsers="allUsers"
        @cancel="handleCancel"
        @ok="userOk" />
      <evaluate-form
        ref="evaluateModal"
        :visible="evaVisible"
        :rule="rule"
        :year="year"
        :version="version"
        @cancel="handleCancel"
        @ok="evaluateSubmit" />
    </a-card>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import CreateForm from './CreateForm'
import EvaluateForm from './EvaluateForm'
import UserForm from './UserForm'
import {
  generaterformance,
  verifyPerformance,
  allocatePerformance,
  searchPerformance,
  evaluatePerformance,
  getRelatedVersions, // .查询已关联绩效参数年份版本
  deleteAllocate, // 绩效删除
  initialPerformance
} from '@/api/incentive'
import { allStaff } from '@/api/manage'
import { columns, mockData } from './mock'
import { mapGetters } from 'vuex'
// import { isInMenu } from '../../config'

export default {
  name: 'Performance',
  props: {
    contractInfo: {
      type: Object,
      default: null
    }
  },
  components: {
    STable,
    CreateForm,
    EvaluateForm,
    Ellipsis,
    UserForm
  },
  data () {
    this.incomeExpensesColumns = []
    this.fileColumns = []
    this.columns = columns
    return {
      list: [],
      isAdd: false,
      isEdit: false,
      visible: false,
      loading: false,
      suppliers: undefined,
      confirmLoading: false,
      incomes: undefined,
      incomeRecord: undefined,
      income: undefined,
      year: undefined,
      version: undefined,
      // 已经发放，则选版本的下拉选disable
      hasGrant: false,
      versionName: undefined,
      // 已关联的所有版本
      allVersion: [],
      allUsers: [],
      rule: {},
      // 考核表单
      evaVisible: false,
      // 分配表单
      userVisible: false,
      labels: [
        { label: '全职业务员', value: 1 },
        { label: '兼职业务员', value: 2 },
        { label: '项目经理', value: 3 },
        { label: '策划组', value: 4 },
        { label: 'UI设计&动效创意组 ', value: 5 },
        { label: '程序组 ', value: 6 },
        { label: '内容组(定制软件)', value: 7 },
        { label: '硬件开发组(定制硬件)', value: 8 },
        { label: '行政管理', value: 9 }
      ],
      // 附件
      files: undefined,
      fileTabLoading: false,
      fileCreateVisible: false,
      physicalSurveyCurrRowId: null,
      loadData: parameter => {
        mockData.map((item, ind1) => {
        // this.list.map((item, ind1) => {
          item.level = 1
          item.id = ind1
          // 二级数据加上level
          if (item.children) {
            item.children.map((_sub, ind2) => {
              _sub.level = 2
              _sub.id = `${ind1}-${ind2}`
              // 三级数据加上level
              if (_sub.children) {
                _sub.children.map((third, ind3) => {
                  third.level = 3
                  third.id = `${ind1}-${ind2}-${ind3}`
                })
              }
            })
          }
        })
        console.log(mockData)
        return Promise.resolve({ data: mockData, pagination: null })
      }
    }
  },
  computed: {
    ...mapGetters(['menu'])
  },
  created () {},
  watch: {
    userVisible: function (v) {
      if (this.allUsers.length < 1) {
        this.getUsers()
      }
    },
    contractInfo: function (v) {
      if (v.contractId) {
        this.initPerformance({ contractId: v.contractId })
        getRelatedVersions({ contractId: v.contractId }).then(res => {
        this.hasGrant = res.data.some(item => item.flg === 'Y')
        this.allVersion = res.data.map(item => `${item.year}/${item.version}`)
      })
      }
    },
    versionName: function (v) {
      if (v !== `${this.year}/${this.version}`) {
        try {
          const [year, version] = v.split('/')
          this.initPerformance({ contractId: this.contractInfo.contractId, year, version })
        } catch (e) {}
      }
    }
  },
  mounted () {
    this.getUsers()
  },
  methods: {
    async deletePer (record) {
      const res = await deleteAllocate({ incentiveId: record.incentiveId })
      if (res.code === 0) {
        this.initPerformance()
      }
    },
    async initPerformance (param) {
      this.loading = true
      this._initPerformance(param).finally(() => {
        this.loading = false
      })
    },
    async _initPerformance (param) {
      if (param) {
        const listResp = await initialPerformance(param)
        if (listResp.data && listResp.data.length) {
          this.year = listResp.year
          this.version = listResp.version
          this.versionName = `${this.year}/${this.version}`
          // 拼接上分配比例
          const evas = await searchPerformance({
            year: this.year,
            version: this.version,
            contractId: param.contractId
          })
          this.loading = false
          this.list = listResp.data.map(item => {
            item.evaluation = evas.data[item.job2]
            return item
          })
          this.$refs.table.refresh()
        }
      } else {
        this._initPerformance({ contractId: this.contractInfo.contractId, year: this.year, version: this.version })
      }
    },
    createList () {
      this.visible = true
    },
    async refresh () {
      const contractId = this.contractInfo.contractId
      if (!contractId) return
      getRelatedVersions({ contractId }).then(res => {
        this.hasGrant = res.data.some(item => item.flg === 'Y')
        this.allVersion = res.data.map(item => `${item.year}/${item.version}`)
        this.initPerformance({ contractId })
      })
    },
    evaluateSubmit (param) {
      evaluatePerformance({
        contractId: this.contractInfo.contractId,
        year: this.year,
        version: this.version,
        job2: this.rule.job2,
        ...param
      }).then(() => {
        this.initPerformance({ contractId: this.contractInfo.contractId, version: this.version, year: this.year })
        this.handleCancel()
      })
    },
    async userOk (values) {
      const { incentiveName, performanceConfigId, job2 } = this.rule

      const res = await allocatePerformance({
        incentiveName,
        performanceConfigId,
        job2,
        contractId: this.contractInfo.contractId,
        ...values
      })
      if (res.code === 0) {
        this.initPerformance()
        this.handleCancel()
      }
    },
    getUsers () {
      allStaff().then(res => {
        this.allUsers = res.data
      })
    },
    async handleOk (values) {
      const [year, version] = values.version
      this.year = year
      this.version = version

      const res = await verifyPerformance({ year, version })

      if (res.code !== 0) return
      await generaterformance({ year, version, contractId: this.contractInfo.contractId })
      this.refresh()
      // 拼接上分配比例
      // const evas = await searchPerformance({ year, version, contractId: this.contractInfo.contractId })

      // this.list = listResp.data.map(item => {
      //   item.evaluation = evas.data[item.job2]
      //   return item
      // })
      this.visible = false
      this.$refs.table.refresh()
    },
    showEvaModal (record) {
      this.evaVisible = true
      this.rule = record
    },
    showUserModal (record) {
      this.userVisible = true
      this.rule = record
    },
    handleCancel () {
      this.visible = false
      this.evaVisible = false
      this.userVisible = false
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.level === 1 ? 'white' : record.level === 2 ? '#f0f0f0' : 'rgb(220, 220, 220)'
        },
        on: {
          click: event => {
            // this.physicalSurveyCurrRowId = record.id
            // this.conRecord = record
          }
        }
      }
    }
  }
}
</script>
